Cache policy
The cache policy enables you to cache the upstream response (content, status, and headers) and avoid subsequent calls to the backend.
This policy relies on a cache resource that you define at the API level and lets the underlying cache system follow the API lifecycle (stop / start). The system automatically creates the cache resource when you attach the cache policy rule to an API.
You can bypass cache by adding a cache=BY_PASS query parameter or by providing an X-Gravitee-Cache=BY_PASS HTTP header.
If you have a multi-node Gateway cluster, each node caches the API request because the cache is JVM-centric.
Timing
| On Request | On Response |
|---|---|
| X |
Configuration
| Property | Required | Description | Type | Default |
|---|---|---|---|---|
cacheName | yes | The cache resource used to store the element. | string | |
key | no | The key used to store the element (supports EL). | string | |
timeToLiveSeconds | yes | Time to live of the element in cache. | integer | 600 (10 minutes) |
methods | no | The method to cache. | array of strings | [GET,OPTIONS,HEAD] |
responseCondition | no | Add an extra condition (with Expression Language) based on the response to activate cache. For example, use {#upstreamResponse.status == 200} to only cache 200 responses status. If you do not specify a responseCondition, the policy caches all 2xx responses by default. | string | |
useResponseCacheHeaders | no | Time to live based on 'Cache-Control' and/or 'Expires' headers from backend response. | boolean | false |
scope | yes | Cached response can be set for a single consumer (application) or for all applications. Caution If you use an \"API\" scope, the policy shares data between all consumers. | API/APPLICATION | APPLICATION |
Examples
Key based on the productId query parameter:
"key": "{#request.params['productId']}"
Key based on the api-key of the consumer:
"key": "{#request.headers['X-Gravitee-Api-Key']}"
Key based on an API’s property and a query parameter:
"key": "{#properties['siteID']}-{#request.params['productId']}"
Configuration example:
"cache": {
"cacheName": "policy-cache",
"key": "{#request.params['productId']}",
"timeToLiveSeconds": 600,
"useResponseCacheHeaders": false,
"scope": "APPLICATION",
"methods": ["POST"],
"responseCondition": "{#upstreamResponse.status == 201}"
}